package com.dongbao.entity;

import org.jetbrains.idea.maven.indices.MavenArtifactSearchResult;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.util.Arrays;
import java.util.List;

public final class MyTreeModel implements TreeModel {
    List<? extends MavenArtifactSearchResult> myItems;

    public MyTreeModel(List<? extends MavenArtifactSearchResult> items) {
        myItems = items;
    }

    @Override
    public Object getRoot() {
        return myItems;
    }

    @Override
    public Object getChild(Object parent, int index) {
        return getList(parent).get(index);
    }

    @Override
    public int getChildCount(Object parent) {
        List list = getList(parent);
        assert list != null : parent;
        return list.size();
    }

    public List getList(Object parent) {
        if (parent == myItems) return myItems;
        if (parent instanceof MavenArtifactSearchResult) {
            return Arrays.asList(((MavenArtifactSearchResult)parent).getSearchResults().getItems());
        }
        return null;
    }

    @Override
    public boolean isLeaf(Object node) {
        return node != myItems && (getList(node) == null || getChildCount(node) < 2);
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        return getList(parent).indexOf(child);
    }

    @Override
    public void valueForPathChanged(TreePath path, Object newValue) {
    }

    @Override
    public void addTreeModelListener(TreeModelListener l) {
    }

    @Override
    public void removeTreeModelListener(TreeModelListener l) {
    }
}